import { useSetState } from 'ahooks'
import styles from './index.module.less'
import Add from '@/svg/add'
import cm from 'classnames'
import { useEffect } from 'react'
import AddAccount from './add-account'
import { hidePhone } from '@/utils/utils'
import Button from '@/components/button'
import { getUserAccount, getUserAsset, deleteUserAccount, userWithdrawal } from '@/api/user'
import Toast from '@/components/toast'
import Big from 'big.js'
import WarnSvg from '@/svg/warn'
import { pick } from 'lodash-es'

//处理提现金额异常逻辑
const handleMoneyError = (money, assetMoney) => {
  if (!money) {
    return {
      msg: '请输入提现金额',
      pass: false,
    }
  } else if (!/^\d+(.\d{1,2})?$/.test(money)) {
    return {
      msg: '请输入合法的金额',
      pass: false,
    }
  } else if (money > assetMoney) {
    return {
      msg: '可提现金额不足，请重新输入',
      pass: false,
    }
  } else if (money < 100) {
    return {
      msg: '最低可提现金额为100，请重新输入',
      pass: false,
    }
  } else if (money > 50000) {
    return {
      msg: '支付方式单笔转账限额为5万元，请分批提现',
      pass: false,
    }
  } else {
    return { pass: true }
  }
}

const Index = () => {
  const [formInfo, setFormInfo] = useSetState({
    asset: 0,
    list: [],
    delCurrent: {},
  })
  const addAccount = () => {
    getAccount()
  }

  const delAccount = async (accountId) => {
    const res = await deleteUserAccount({ accountId })
    if (!res.code) {
      Toast.normal('删除账户成功')
      getAccount()
    }
  }

  const chooseAccount = (item) => {
    setFormInfo({ accountId: item.id, accountPhone: item.phone })
  }
  const submit = async () => {
    const handleMoney = handleMoneyError(formInfo.money, formInfo.asset)
    setFormInfo({
      noMoney: !handleMoney.pass,
      moneyErr: handleMoney.msg,
      noAccount: !formInfo.list.length || !formInfo.accountId,
    })
    if (!handleMoney.pass || !formInfo.accountId) {
      return
    }
    const params = {
      amount: Big(formInfo.money).times(100).toFixed(2).toString(),
      ...pick(formInfo, ['accountId', 'remark']),
    }
    const res = await userWithdrawal(params)
    if (!res.code) {
      Toast.normal('提现申请已提交，您将在3-5个工作日内收到款项，请耐心等待')
      fetchAsset()
      setFormInfo({
        accountId: '',
      })
    }
  }

  // 获取资产
  const fetchAsset = async () => {
    const res = await getUserAsset()
    if (!res.code) {
      setFormInfo({
        asset: Big(res.data.accountBalance || 0)
          .div(100)
          .toFixed(2)
          .toString(),
      })
    }
  }
  // const 获取收款账户
  const getAccount = async () => {
    const res = await getUserAccount()
    if (!res.code) {
      setFormInfo({ list: res.data?.list || [] })
    }
  }
  useEffect(() => {
    fetchAsset()
    getAccount()
  }, [])

  return (
    <div className={styles.home}>
      <p className={styles.title}>提现</p>
      <hr className={styles.line} />
      <p className={styles.titleLabel}>
        <span className={styles.red}>*</span>
        <span>提现金额：</span>
        {formInfo.noMoney && <span className={styles.error}>{formInfo.moneyErr}</span>}
      </p>
      <div className={styles.moneyBox}>
        <input
          maxLength={100}
          type="text"
          placeholder="请输入提现金额"
          onInput={(e) => setFormInfo({ money: e.currentTarget.value })}
        />
        <span>元</span>
      </div>
      <p className={styles.moneyTips}>可提现余额：{formInfo.asset}元</p>
      <p className={styles.titleLabel}>
        <span className={styles.red}>*</span>
        <span>收款账户：</span>
        {formInfo.noAccount && <span className={styles.error}>请选择收款账户</span>}
      </p>
      <div className={styles.accountBox}>
        {formInfo.list.map((item) => {
          return (
            <div
              key={item.id}
              className={cm(styles.accountItem, formInfo.accountId === item.id ? styles.accountActive : '')}
            >
              <div className={styles.box} onClick={() => chooseAccount(item)}>
                <span className={styles.checkbox}></span>
                <img src="/images/alipay.png" alt="" className={styles.platform} />
                <span className={styles.platformName}>支付宝</span>
                <span>{hidePhone(item.account)}</span>
              </div>
              <div className={styles.del}>
                <span onClick={() => setFormInfo({ delCurrent: { open: true, id: item.id } })}>删除</span>
                {formInfo.delCurrent.open && formInfo.delCurrent.id === item.id && (
                  <div className={styles.delPanel}>
                    <div className={styles.warnBox}>
                      <WarnSvg width={14} fill="var(--theme-color)" />
                      <span>是否确认删除该收款账户？</span>
                    </div>
                    <div className={styles.btnGroup}>
                      <Button
                        className={cm(styles.btn, styles.btn1)}
                        onClick={() => setFormInfo({ delCurrent: { open: false, id: item.id } })}
                      >
                        取消
                      </Button>
                      <Button className={cm(styles.btn, styles.btn2)} onClick={() => delAccount(item.id)}>
                        确认
                      </Button>
                    </div>
                  </div>
                )}
              </div>
            </div>
          )
        })}
      </div>
      <div className={styles.addAccountBox}>
        <div className={styles.addAccount} onClick={() => setFormInfo({ showAdd: true })}>
          <Add className={styles.svg} />
          <span>添加收款账户</span>
        </div>
        {formInfo.showAdd && (
          <AddAccount
            addAccount={addAccount}
            className={styles.showPanel}
            onClose={() => setFormInfo({ showAdd: false })}
          />
        )}
      </div>
      <p className={styles.titleLabel}>
        <span>备注：</span>
      </p>
      <input
        type="text"
        className={styles.remarksInput}
        maxLength={20}
        placeholder="备注会展示在交易明细中，不超过20字"
        onInput={(e) => setFormInfo({ remark: e.currentTarget.value })}
      />
      <Button className={styles.submit} onClick={submit}>
        提交
      </Button>
    </div>
  )
}

export default Index
